package org.jeecg.common.util.sm.utils;



import org.jeecg.common.util.sm.bean.KeyAndIV;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

public class SM4KeyUtils {

    public static String SM4KeyGenerator() {
        // 创建一个SecureRandom实例
        SecureRandom secureRandom = new SecureRandom();
        // 生成一个16字节（128位）的随机密钥
        byte[] sm4Key = new byte[16];
        secureRandom.nextBytes(sm4Key);
        // 将密钥转换为32位的十六进制字符串
        String hexKey = bytesToHex(sm4Key);
        // 输出密钥
        return hexKey;
    }

    public static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }


    public static byte[] getSm4Encrypt(String transformation, String source, KeyAndIV keyAndIV) {
        byte[] sm4EncryptCBCByte;
        try {
            Key keys = new SecretKeySpec(keyAndIV.getKey(), "SM4");

            Cipher out = Cipher.getInstance(transformation, "BC");
            IvParameterSpec ivSpec = new IvParameterSpec(keyAndIV.getIv());
            out.init(Cipher.ENCRYPT_MODE, keys, ivSpec);
            sm4EncryptCBCByte = out.doFinal(source.getBytes());
        } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException |
                 InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
        return sm4EncryptCBCByte;
    }
}
